package notification

import gomail "gopkg.in/gomail.v2"

type EmailNotification interface {
	EMAIL(to, toName string) error
}

type IEmailNotification struct {
	From     string
	FromName string
	SMTPHost string
	Password string
	Header   string
	Body     string
}

func NewEmailNotification(from, fromName, smtpHost, password, header, body string) EmailNotification {
	return &IEmailNotification{
		From:     from,
		FromName: fromName,
		SMTPHost: smtpHost,
		Password: password,
		Header:   header,
		Body:     body,
	}
}

func (s *IEmailNotification) EMAIL(to, toName string) error {
	m := gomail.NewMessage()
	m.SetAddressHeader("From", s.From, s.FromName) // 发件人 邮箱--名字
	m.SetHeader("To",                              // 收件人   邮箱--名字
		m.FormatAddress(to, toName),
	)
	m.SetHeader("Subject", s.Header)                                // 邮件主题
	m.SetBody("text/html", s.Body)                                  // 正文（html格式）
	d := gomail.NewPlainDialer(s.SMTPHost, 465, s.From, s.Password) // 发送邮件服务器、端口、发件人账号、发件人密码(需要去qq邮箱开启smtp服务)
	if err := d.DialAndSend(m); err != nil {
		return err
	}
	return nil
}
